package com.example.spider.cluster.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GetObjectRequest;
import lombok.Data;
import org.shoulder.core.exception.BaseRuntimeException;

import java.io.File;

@Data
public class OssDownloader {

    private final OSS ossClient;

    private final String bucketName;

    public OssDownloader(OSS ossClient, String bucketName) {
        this.ossClient = ossClient;
        this.bucketName = bucketName;
    }

    public void download(String remotePath, String targetPath, boolean deleteRemote) {
        try {
            // 下载Object到本地文件，并保存到指定的本地路径中。如果指定的本地文件存在会覆盖，不存在则新建。
            // 如果未指定本地路径，则下载后的文件默认保存到示例程序所属项目对应本地路径中。
            ossClient.getObject(new GetObjectRequest(bucketName, remotePath), new File(targetPath));
            if (deleteRemote) {
                ossClient.deleteObject(bucketName, remotePath);
            }
        } catch (Exception oe) {
            throw new BaseRuntimeException(oe);
        }
    }

}